package cn.baage;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Log4j2
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    private final ExpirationMessageDispatcher expirationMessageDispatcher;

    @Autowired
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, ExpirationMessageDispatcher expirationMessageDispatcher) {
        super(listenerContainer);
        this.expirationMessageDispatcher = expirationMessageDispatcher;
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("过期消息 key:{} pattern:{}", expiredKey, new String(pattern, StandardCharsets.UTF_8));
        expirationMessageDispatcher.dispatchExpiredKey(expiredKey);
    }

}
